/**
 * 审核
 * @constructor
 */
function Review() {

    this.passType = '1' // 审核,通过,驳回tab切换
    this.rolesArr = []      // 用户权限id数组
    this.applyListJson  // 缓存请求数据
    this.emptyHouseList // 可用房间列表

    var _this = this

    this.init = function() {

        this.initTab()
        this.initDialog()

        // 获取权限列表
        var rolesList = JSON.parse(localStorage.getItem('roles'))

        rolesList.forEach(function(role) {
            _this.rolesArr.push(role.roleId)
        })


        $('#myTabs span:eq(0)').click()

        // 分页回调
        window.paginationCallback = function (page_index) {
            if(!isPostBack) {
                _this.getApplyList(_this.passType, page_index+1);
            }
        }

        // 审核按钮
        window.applyEditTipFn = function(passFlag) {

            var applyRequestId = $('.applyBtnBox').attr('data-requestId')

            // 驳回
            if (passFlag == '-1') {

                return bootbox.prompt({
                    title: '请输入驳回原因!',
                    buttons: {
                        confirm: {
                            label: '驳回',
                            className: 'btn-danger'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default'
                        }
                    },
                    callback: function(reason) {
                        // 取消
                        if (reason == null) {
                            return
                        }
                        if (!reason) {
                            return tipModal('icon-checkmark', '请输入驳回原因')
                        }

                        _this.reviewHandle(applyRequestId, passFlag, reason)
                    }
                })
            }

            _this.reviewHandle(applyRequestId, passFlag)

        }

    }

    // tab 事件绑定
    this.initTab = function() {

        // tab 切换
        $('#myTabs span').not('.active').bind('click', function selApply(){
            $('.t-apply-box .t-box-title-btn').not('.btnSel').unbind('click')
            $(this).siblings().removeClass('btnSel')
            $(this).addClass('btnSel')
            _this.passType = $(this).attr("data-type")

            window.isPostBack = true
            _this.getApplyList(_this.passType, 1)
            $('.t-apply-box .t-box-title-btn').not('.btnSel').bind('click',selApply)
        });
    }

    // 弹窗初始化
    this.initDialog = function() {

        // 审核
        $('#applyTableData').on('click', '.product-item-check', function() {
            _this.renderDetData(this, 'applyModalDet')
        })

        // 编辑
        $('#applyTableData').on('click', '.product-item-edit', function () {
            _this.renderDetData(this, 'applyModalEdit')

            $('.selectpicker').selectpicker()

            // 编辑框打开 请求默认房间类型下的房间列表数据
            _this.houseTypeChange(function() {
                $('#editBuildingNo').val($('#hiddenBuildingId').val()).selectpicker('refresh').trigger('change')
                $('#editRoomNo').val($('#hiddenRoomId').val()).selectpicker('refresh')
            })
        })

        /***** 三级联动 *****/
        // 选择房间类型
        $('#applyModal').on('change', '#dormitoryType', function(event) {
            event.stopPropagation();

            $('#editRoomNo').html('').selectpicker('refresh')
            _this.houseTypeChange()
        })

        // 选择楼栋
        $('#applyModal').on('change', '#editBuildingNo', function(value) {

            var buildingId = $(this).val()

            var list = _this.emptyHouseList
            var rooms
            for ( var i = 0, l = list.length; i < l; i++ ) {
                if (list[i].buildingid == buildingId) {
                    rooms = list[i].rooms
                    break
                }
            }

            _this.renderHouseSel(rooms)

        })
        /***** /三级联动 *****/


        // 确认修改
        $('#applyModal').on('click', '#editConfirm', function() {

            var applyRequestId = $('#hiddenApplyId').val();               // 申请号
            var startDate = $('.dormitoryTimeS').val();
            var endDate = $('.dormitoryTimeE').val();
            var roomId = $('#editRoomNo').val();               // 房间id

            if(applyRequestId != '' && roomId != '' && startDate != '' && endDate != ''){

                if (startDate >= endDate) {
                    return tipModal('icon-cross', '开始时间不能大于结束时间！')
                }

                $("#applyModal").modal("hide");
                PostForm("/cwp/front/sh/apartment!execute", "uid=R015&applyRequestId=" + applyRequestId + "&roomId=" + roomId + "&startDate=" + startDate + "&endDate=" + endDate + '&passFlag=0', "", function(result){
                    if(result.returnCode == 0){
                        tipModal("icon-checkmark", result.returnMessage);
                        // 重绘待审核列表
                        _this.getApplyList(_this.passType, 1);
                    }else{
                        tipModal("icon-cross", result.returnMessage);
                    }
                }, '');
            }else{
                tipModal("icon-cross", '请输入正确参数');
            }
        })
    }

    // 根据 id 查找列表中数据并渲染
    this.renderDetData = function(elem, templateId) {
        var applyRequestId = $(elem).attr('data-id')

        var list = _this.applyListJson.beans
        var detData = {}

        for(var i = 0; i< list.length; i++) {
            if (list[i].applyRequestId == applyRequestId) {
                detData = list[i]
                break
            }
        }

        template.helper('findRole', _this.findRole);

        detData.roles = _this.rolesArr

        $('#applyModal .modal-content').html(template(templateId, detData))
        $('#dormitoryType').val(detData.requestRoomType)

        $("#applyModal").modal({
            keyboard: true,
            backdrop: 'static'
        },'show.bs.modal', centerModal());

        // 精确到分
        $(".form_date_hour_start").not('.readonly').datetimepicker({
            language: 'zh-CN',
            format: "yyyy-mm-dd hh:ii:00",
            autoclose: true,
            minView: "hour",
            maxView: "decade",
            todayBtn: true,
            clearBtn: true
        });
    }

    // 待审核列表
    this.getApplyList = function(passType, pageIndex){


        $.getJSON('../../static/json/boardroomManger/apartment_R014.json',function(data){
            var loaderTable = new LoaderTable('', 'applyTableData', '/cwp/front/sh/apartment!execute', "uid=R014&delFlag=1&passFlag=" + passType,
                pageIndex || 1, 10, _this.renderApplyList, null)

            // loaderTable.Display()
            loaderTable.loadSuccessed(data);
        });
    };

    // 审核处理
    this.reviewHandle = function(applyRequestId, passFlag, reason) {

        PostForm("/cwp/front/sh/apartment!execute", "uid=R015&applyRequestId="+ applyRequestId +"&passFlag=" + passFlag + (reason ? '&failReason=' + reason : ''), "", function(result){
            if(result.returnCode == 0){

                $("#applyModal").modal("hide");

                tipModal("icon-checkmark", result.returnMessage);
            }else{
                tipModal("icon-checkmark", result.returnMessage);
            }
            // 重绘待审核列表
            _this.getApplyList(_this.passType, 1);
        }, '');
    }

    // 渲染申请列表
    this.renderApplyList = function(result){
        _this.applyListJson = result;
        if(result.returnCode == 0){
            var alertHtml;
            if(result.beans.length == 0){
                alertHtml = "<h2 style='text-align: center;'>暂无审核信息</h2>";
            }else{
                template.helper('roomTypeDictdataIdName', function(inp) {
                    if(inp == "1009033") {
                        return '大型会议室';
                    } else if(inp == "1009022"){
                        return '中型会议室';
                    } else if(inp == "1009011"){
                        return '小型会议室';
                    }else if(inp == "1009044"){
                        return '超大型会议室';
                    }
                });
                template.helper('passFlagType', function(inp) {
                    // 只有宿舍主管有审核权限
                    if(inp == '1' && _this.findRole(_this.rolesArr, [60])){
                        return "审核";
                    }else{
                        return "详情";
                    }
                });

                alertHtml = template('applyListTpl',result);
            }
            $('#applyTableData').html(alertHtml);
        }else{
            tipModal("icon-cross", result.returnMessage);
        }
    };

    // 房间类型改变
    this.houseTypeChange = function(cb) {
        PostForm('/cwp/front/sh/apartment!execute', 'uid=R016_2&startDate=' + $('.dormitoryTimeS').val() + '&endDate=' + $('.dormitoryTimeE').val() + '&roomTypeDictdataId=' +$('#dormitoryType').val(), 'get', function(result) {
            if (+result.returnCode) {

                $('#editBuildingNo, #editRoomNo').html('').selectpicker('refresh')
                return tipModal('icon-cross', result.returnMessage)
            }

            _this.emptyHouseList = result.object        // 暂存数据
            _this.renderBuildingSel(result.object)

            if (cb) {
                cb()
            }
        })
    }

    // 渲染楼栋 select 数据
    this.renderBuildingSel = function(list) {
        var html = ''
        list.forEach(function(item) {
            html += '<option value="' + item.buildingid + '">' + item.buildingName + '</option>'
        })

        $('#editBuildingNo').html(html).selectpicker('refresh')
    }

    // 渲染房间 select 列表
    this.renderHouseSel = function(list) {
        var html = ''
        list.forEach(function(item) {
            html += '<option value="' + item.roomId + '">' + item.roomNumber + '</option>'
        })

        $('#editRoomNo').html(html).selectpicker('refresh')
    }

    // 权限查找
    this.findRole = function(roles, item) {

        var flag = false
        for (var i = 0, l = item.length; i < l; i++) {
            if (roles.indexOf(item[i]) != -1) {
                flag = true
                break;
            }
        }

        return flag
    }
}


$(function() {
    new Review().init();
})